/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fxbattle.client.model;

import java.util.Map;

import edu.stsci.CoSI.CosiInt;
import edu.stsci.CoSI.collections.CosiMap;

/**
 *
 * @author spina
 */
public class BattleMap {

    private final Map<Location, BattleHex> map = CosiMap.hashMap();
    private final CosiInt minX = new CosiInt();
    private final CosiInt maxX = new CosiInt();
    private final CosiInt minY = new CosiInt();
    private final CosiInt maxY = new CosiInt();

    public void setHex(BattleHex iHex){
    	setHex(iHex, iHex.getLocation());
    }
    
    private void setHex(BattleHex iHex, Location iLoc){
    	int x = iLoc.getX();
    	int y = iLoc.getY();
    	minX.set((minX.get() == null) ? x : Math.min(minX.get(), x));
    	maxX.set((maxX.get() == null) ? x : Math.max(maxX.get(), x));
    	minY.set((minY.get() == null) ? y : Math.min(minY.get(), y));
    	maxY.set((maxY.get() == null) ? y : Math.max(maxY.get(), y));
    	map.put(iLoc, iHex);
    }
    
    public void assignNeighbors(){
    	if(minX == null){
    		throw new IllegalStateException("Can't assign Neighbors, there are no Hexes!");
    	}
    	for(int x = getMinX(); x <= getMaxX(); x++){
    		for(int y = getMinY(); y <= getMaxY(); y++){
    			BattleHex lHex = getHex(x, y);
    			if( ! (lHex instanceof BoundaryHex) ){
	    			for(Direction lDir: Direction.values()){
	    				lHex.setAdjacentHex(lDir, getHex(lDir.goFrom(lHex.getLocation())));
	    			}
    			}
    		}
    	}
    }

    public int getMinX(){ return minX.get(); }
    public int getMaxX(){ return maxX.get(); }
    public int getMinY(){ return minY.get(); }
    public int getMaxY(){ return maxY.get(); }

    public boolean hexExists(Location iLoc){
    	return map.get(iLoc) != null;
    }
    
    public BattleHex getHex(Location iLoc){
    	if( ! hexExists(iLoc) ){
    		map.put(iLoc, BoundaryHex.getBoundary(iLoc));
    	}
    	return map.get(iLoc);
    }
    
    public BattleHex getHex(int x, int y){
    	return getHex(Location.getLocation(x, y));
    }
    
    public static void main(String[] iArgs){
    	System.out.println("Test Driving Battle Map");
        BattleMap test = new BattleMap();
        for(int x = 0; x < 4; x++){
            for(int y = 0; y < 5; y++){
            	BattleHex lHex = new BattleHex(x,y);
            	lHex.setElevation( (int) (Math.random() * 5) );
                test.setHex(new BattleHex(x, y));
                
                if(y == 0){
                	test.getHex(x, y).conquered(new Army(Player.getPlayer("name", java.awt.Color.GREEN), 10));
                }
            }
        }
        test.assignNeighbors();
        System.out.println("Done Test Driving");
    }

}
